package com.zby.charity.utils;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.zby.charity.common.ErrorCode;
import com.zby.charity.constant.UserConstant;
import com.zby.charity.entity.UserEntity;
import com.zby.charity.exception.BusinessException;
import com.zby.charity.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;


@Component
@ConfigurationProperties(prefix = "oss")
public class OssConfig {
    private static final String DOMAIN = "http://spi0eju60.hn-bkt.clouddn.com";
    private String accessKey;
    private String secretKey;
    private String bucket;

    @Autowired
    public UserService userService;
    public static String getRandomImg() {
        String[] imgs = {
                "https://haogongyi.org.cn/Uploads/image/20230904/product_list_64f597ac752f7.jpeg",
                "https://haogongyi.org.cn/Uploads/image/20230413/product_list_6437a6c4a34e7.jpeg",
                "https://haogongyi.org.cn/Uploads/image/20220913/product_list_631fe2df4d4d7.jpeg",
                "https://haogongyi.org.cn/Uploads/image/20220825/product_list_63072a13c670f.jpeg",
                "https://haogongyi.org.cn/Uploads/image/20230425/product_list_64478b14da97e.jpeg"
        };
        return imgs[(int) (Math.random() * 5)];
    }

    public void setAccessKey(String accessKey) {
        this.accessKey = accessKey;
    }

    public void setSecretKey(String secretKey) {
        this.secretKey = secretKey;
    }

    public void setBucket(String bucket) {
        this.bucket = bucket;
    }
    public String uploadImg(MultipartFile file) {

        Configuration cfg = new Configuration(Region.autoRegion());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本


        UploadManager uploadManager = new UploadManager(cfg);

        String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String key = "project/"+format + "/" + file.getOriginalFilename();
        try {
            InputStream inputStream = file.getInputStream();
            Auth auth = Auth.create(accessKey, secretKey);//创建凭证
            String upToken = auth.uploadToken(bucket); //上传凭证
            try {
                Response response = uploadManager.put(inputStream, key, upToken, null, null);
                //解析上传成功的结果
                if (response.isOK()) {
                    DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                    String url = DOMAIN + "/" + putRet.key;
                    return url;
                } else {
                    return getRandomImg();
                }
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (Exception ex) {
            //ignore  异常类型 改大一点
            System.err.println("文件读取失败: " + ex.getMessage());
        }

        return getRandomImg();
    }
    public String uploadImg1(MultipartFile file) {

        Configuration cfg = new Configuration(Region.autoRegion());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本


        UploadManager uploadManager = new UploadManager(cfg);

        String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String key = "posts/"+format + "/" + file.getOriginalFilename();
        try {
            InputStream inputStream = file.getInputStream();
            Auth auth = Auth.create(accessKey, secretKey);//创建凭证
            String upToken = auth.uploadToken(bucket); //上传凭证
            try {
                Response response = uploadManager.put(inputStream, key, upToken, null, null);
                //解析上传成功的结果
                if (response.isOK()) {
                    DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                    String url = DOMAIN + "/" + putRet.key;
                    return url;
                } else {
                    return getRandomImg();
                }
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (Exception ex) {
            //ignore  异常类型 改大一点
            System.err.println("文件读取失败: " + ex.getMessage());
        }

        return getRandomImg();
    }
    public boolean uploadImg(MultipartFile file,Integer id) {

        Configuration cfg = new Configuration(Region.autoRegion());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本


        UploadManager uploadManager = new UploadManager(cfg);

        String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String key = format + "/" + file.getOriginalFilename();
        try {
            InputStream inputStream = file.getInputStream();
            Auth auth = Auth.create(accessKey, secretKey);//创建凭证
            String upToken = auth.uploadToken(bucket); //上传凭证
            try {
                Response response = uploadManager.put(inputStream, key, upToken, null, null);
                //解析上传成功的结果
                if (response.isOK()) {
                    DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                    String url = DOMAIN + "/" + putRet.key;
                    UserEntity byId = userService.getById(id);
                    if (byId == null)
                        throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
                    byId.setAvatarUrl(url);
                    boolean b = userService.updateById(byId);
                    if (!b)
                        throw new BusinessException(ErrorCode.SYSTEM_ERROR);
                    return true;
                } else {
                    return false;
                }
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (Exception ex) {
            //ignore  异常类型 改大一点
            System.err.println("文件读取失败: " + ex.getMessage());
        }

        return false;
    }
}
